package com.alexb.tasksreport.resource;

import java.text.ParseException;
import java.util.Collection;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import com.alexb.tasksreport.model.Task;
import com.alexb.tasksreport.util.PMF;

@Path("/tasks")
public class TasksResource {

    @GET
    @Produces("application/json")
    public Collection<Task> list() {
    	
    	Collection<Task> allTasks;
    	
    	PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
        	Query query = pm.newQuery(Task.class);
        	allTasks = pm.detachCopyAll((Collection<Task>) query.execute());
        } finally {
            pm.close();
        }
    	
        return allTasks;
    }

    @POST
    @Produces("application/json")
    public Task add(@FormParam("id") Long id, @FormParam("label") String label,
			@FormParam("description") String description,
			@FormParam("ownerId") Long ownerID) throws ParseException {
    	
    	Task task = new Task();
    	task.setId(id);
		task.setLabel(label);
		task.setDescription(description);
		task.setOwnerID(ownerID); 	
    	PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
        	pm.makePersistent(task);
        } finally {
            pm.close();
        }
    	
        return task;
    }
}
